package com.dullwolf.utils;

import io.jboot.Jboot;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.util.Map;

public class HttpRequest {

    private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();

    /**
     * get请求 (带token)
     * @param url 请求地址
     * @param token 请求头
     */
    public static String doGet(String url,String token){
        String result = null;
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse httpResp = null;
        try {
            //设置请求和传输超时时间
            httpGet.setConfig(requestConfig);
            httpGet.setHeader("token",token);
            httpResp = httpclient.execute(httpGet);
            int statusCode = httpResp.getStatusLine().getStatusCode();
            // 判断是够请求成功
            if (statusCode == HttpStatus.SC_OK) {
                // 获取返回的数据
                result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
            }
        } catch (IOException e) {
            //e.printStackTrace();
        } finally {
            try {
                assert httpResp != null;
                httpResp.close();
                httpclient.close();
            } catch (IOException e) {
                //e.printStackTrace();
            }
        }
        return result;
    }



    public static String doPost(String url) {
        return Jboot.httpPost(url,null);
    }


    public static String doPost(String jsonString, String url) {
        Map<String, Object> map = JsonUtils.getMapByObject(JsonUtils.getJsonObjectByJsonString(jsonString));
        return Jboot.httpPost(url,map);
    }


    /**
     * get请求
     * @param url 请求地址
     */
    public static String doGet(String url){
        return Jboot.httpGet(url);
    }
}
